package cmd

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"gitee/kubehark/kubehark-client/pkg/config"
	"github.com/spf13/cobra"
	"golang.org/x/oauth2"
	"io/ioutil"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/tools/clientcmd/api"
	"net/http"
	"strings"
)

type LoginCmd struct {
	ClusterId string
}

func (this *LoginCmd) SetFlag(command *cobra.Command) {
	command.Flags().StringVarP(&this.ClusterId, "clusterid", "i", "", "clusterid")
}

func NewLoginCmd() *cobra.Command {
	infocmd := &LoginCmd{}
	var Cmd = &cobra.Command{
		Use:   "login",
		Short: "登录",
		Long:  `登录进入集群`,
		Run: func(cmd *cobra.Command, args []string) {
			Login(infocmd.ClusterId)
		},
	}
	infocmd.SetFlag(Cmd)
	return Cmd
}

type Response struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

func Login(clusterid string) {
	// 获取需要的token
	var token *oauth2.Token
	var ok bool
	var err error
	var c *api.Config
	var server string
	r := clientcmd.NewDefaultClientConfigLoadingRules()

	c, err = clientcmd.LoadFromFile(r.GetDefaultFilename())
	if err != nil {
		return
	}
	if err = config.Valid(c); err != nil {
		return
	}

	token, err = getRefreshedToken(nil)
	if err != nil {
		return
	}

	var rawIDToken string
	rawIDToken, ok = token.Extra("id_token").(string)
	if !ok {
		return
	}
	server, err = config.GetCurrentAuthInfoEnvByName(c, "server")
	if err != nil {
		return
	}
	url := server + "/switch/" + clusterid
	method := "GET"
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{
		Transport: tr,
	}
	req, err := http.NewRequest(method, url, strings.NewReader(""))
	if err != nil {
		fmt.Println(err)
		return
	}
	req.Header.Set("Authorization", "Bearer "+rawIDToken)
	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return
	}

	response := Response{}
	err = json.Unmarshal([]byte(string(body)), &response)
	fmt.Println(response.Msg)
	if response.Code == 200 {
		if err = config.SetCurrentClusterID(c, clusterid); err != nil {
			return
		}
		if err = clientcmd.WriteToFile(*c, r.GetDefaultFilename()); err != nil {
			return
		}
	}

}
